import React, { useEffect } from "react";
import { Button, Drawer, Form, Input, Spin } from "antd";
import { useProjectModal } from "hooks/useProjectModal";
import UserSelect from "components/user-select";
import { useAddProject, useEditProject } from "server";
import { useForm } from "antd/lib/form/Form";
import { ErrorBox } from "components/lib";
import styled from "@emotion/styled";

const Container = styled.div`
  height: 80vh;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
`;

const Modal = () => {
  const { visible, close, editingProject, isLoading } = useProjectModal();
  const useMetateProject = editingProject ? useEditProject : useAddProject;
  const { mutateAsync, error, isLoading: mutateLoading } = useMetateProject();

  const [form] = useForm();

  useEffect(() => {
    form.setFieldsValue(editingProject);
  }, [editingProject, form]);

  const onFinish = async (vals: any) => {
    await mutateAsync({ ...editingProject, ...vals });
    form.resetFields();
    closeModal();
  };

  const closeModal = () => {
    form.resetFields();
    close();
  };

  return (
    <Drawer width="100%" visible={visible} onClose={closeModal} forceRender>
      <Container>
        {isLoading && <Spin size="large" />}
        {!isLoading && (
          <>
            <h1>{editingProject ? "编辑项目" : "新建项目"}</h1>
            {error && <ErrorBox error={error} />}
            <Form
              layout="vertical"
              style={{ width: "40rem" }}
              onFinish={onFinish}
              form={form}
            >
              <Form.Item
                label="名称"
                name="name"
                rules={[{ required: true, message: "请输入项目名称" }]}
              >
                <Input placeholder="请输入项目名称" />
              </Form.Item>
              <Form.Item
                label="部门"
                name="organization"
                rules={[{ required: true, message: "请输部门名" }]}
              >
                <Input placeholder="请输部门名" />
              </Form.Item>
              <Form.Item label="负责人" name="personId">
                <UserSelect defaultOptionName="负责人" />
              </Form.Item>
              <Form.Item style={{ textAlign: "right" }}>
                <Button
                  type="primary"
                  htmlType="submit"
                  loading={mutateLoading}
                >
                  提交
                </Button>
              </Form.Item>
            </Form>
          </>
        )}
      </Container>
    </Drawer>
  );
};

export default Modal;
